import {
  ProForm,
  ProFormCheckbox,
  ProFormField,
  ProFormGroup,
  ProFormList,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from "@ant-design/pro-components";
import { useRequest } from "ahooks";
import { DeleteOutlined, PlusOutlined } from "@ant-design/icons";
import { Button, Card, Col, Collapse, Form, Row, Spin, Tabs, message } from "antd";
import React, { useEffect, useState } from "react";
import {
  createApi,
  findApi,
  findApiProjectDetail,
  queryDataSource,
  saveApi,
} from "../../../../../api";
import { useOutletContext, useParams } from "react-router-dom";
import SqlEditor from "../../../../../components/SqlEditor";
import JsEditor from "../../../../../components/JsEditor";

const data = {
  name: "查询接口",
  dataSource: "1",
  path: "/api/queryList",
  method: "POST",
  script: {
    sql: "SELECT * FROM area",
    params: [
      { key: "code", value: "sss" },
      { key: "code", value: "sss" },
    ],
  },
};
const App = () => {
  const [form] = Form.useForm();
  const { projectId, apiId } = useParams();
  const [prefix, setPrefix] = useState("/api");
  const context = useOutletContext();
  console.log("contextcontext", context);
  useRequest(() => findApiProjectDetail({ projectId }), {
    onSuccess(data: any) {
      const prefix = `/api/${data.code}/`
      setPrefix(prefix);
      // form.setFieldValue('prefix',prefix)
    },
  });
  const { run, loading } = useRequest(findApi, {
    manual: true,
    onSuccess(res: any) {
      if (res.script && res.script.params) {
        let params = [];
        Object.keys(res.script.params).forEach((key) => {
          //@ts-ignore
          params.push({ key, value: res.script.params[key] });
        });
        res.script.params = params;
      }

      form.setFieldsValue(res);
    },
  });
  useEffect(() => {
    form.resetFields();
    run({ id: apiId });
  }, [apiId]);
  console.log("datadata", data);
  return (
    <Card>
      <Spin spinning={loading}>
        <ProForm
          submitter={{
            searchConfig: {
              submitText: "保存",
            },
          }}
          onFinish={async (e) => {
            if (e.script && e.script.params) {
              let params = {};
              e.script.params.forEach((item) => {
                params[item.key] = item.value || "";
              });
              e.script.params = params;
            }
            e.projectId = projectId;
            e.prefix = prefix
            if (e.id) {
              await saveApi(e);
            } else {
              await createApi(e);
            }
            message.success("成功");
            // @ts-ignore
            context.refresh();
          }}
          layout="horizontal"
          form={form}
        >
          <Form.Item hidden name="id" />
          <Form.Item hidden name="prefix" />
          <ProFormGroup>
            <ProFormField name="name" label="接口名称" />
          </ProFormGroup>
          <ProFormGroup>
            <ProFormText
              fieldProps={{
                addonBefore: prefix,
                // prefix:'/api/lsdfly'
              }}
              width="md"
              name="suffix"
              label="接口路径"
            />
            <ProFormSelect
              options={[
                {
                  value: "POST",
                  label: "POST",
                },
                {
                  value: "GET",
                  label: "GET",
                },
              ]}
              width="xs"
              name="method"
              label="方法"
            />
          </ProFormGroup>
          <Tabs
            items={[
              {
                label: "SQL",
                key: "sql",
                children: (
                  <div>
                    <Row wrap={false}>
                      <Col span={13} style={{ marginRight: 20 }}>
                        <ProFormField name={["script", "sql"]}>
                          <SqlEditor />
                        </ProFormField>
                        {/* <ProFormTextArea
                          layout="horizontal"
                          name={["script", "sql"]}
                        /> */}
                      </Col>
                      <Col span={11}>
                        <ProFormGroup>
                          <ProFormSelect
                            fieldProps={{
                              fieldNames: {
                                value: "id",
                                label: "name",
                              },
                            }}
                            request={async () => {
                              let res = await queryDataSource({
                                projectId,
                              });
                              return res.data;
                            }}
                            width="md"
                            name={["script", "dataSource"]}
                            label="数据源"
                          />

                          <ProFormCheckbox
                            name={["script", "paginate"]}
                            style={{ marginBottom: 0 }}
                          >
                            分页
                          </ProFormCheckbox>
                        </ProFormGroup>
                        <ProFormList
                          copyIconProps={false}
                          name={["script", "params"]}
                        >
                          <ProFormGroup>
                            <ProFormText
                              width="sm"
                              name="key"
                              fieldProps={{ addonBefore: "参数" }}
                            />
                            <ProFormText
                              width="sm"
                              name="value"
                              fieldProps={{ addonBefore: "值" }}
                            />
                          </ProFormGroup>
                        </ProFormList>
                      </Col>
                    </Row>
                  </div>
                ),
              },
              {
                label: "前置操作",
                key: "前置操作",
                children: <Form.List name='preScript'>
                  {(list, { remove, add }) => {
                    return <div>
                      <Collapse bordered={false} size='small' >
                        {list.map(item => {
                          return <Collapse.Panel extra={<a onClick={() => remove(item.name)}><DeleteOutlined /></a>} header="自定义脚本" key={item.key}>
                            <ProFormField name={[item.name, 'code']}>
                              <JsEditor />
                            </ProFormField>
                            <ProFormText hidden name={[item.name, 'type']} />
                          </Collapse.Panel>
                        })}
                      </Collapse>
                      <Button icon={<PlusOutlined />} style={{ marginTop: 10, marginBottom: 10 }} onClick={() => add({
                        type: 'javascript'
                      })} block type='dashed'>添加前置操作</Button>
                    </div>
                  }}
                </Form.List>
              },
              {
                label: "后置操作",
                key: "后置操作",
                children: <Form.List name='postScript'>
                  {(list, { remove, add }) => {
                    return <div>
                      <Collapse bordered={false} size='small' >
                        {list.map(item => {
                          return <Collapse.Panel extra={<a onClick={() => remove(item.name)}><DeleteOutlined /></a>} header="自定义脚本" key={item.key}>
                            <ProFormField name={[item.name, 'code']}>
                              <JsEditor />
                            </ProFormField>
                            <ProFormText hidden name={[item.name, 'type']} />
                          </Collapse.Panel>
                        })}
                      </Collapse>
                      <Button icon={<PlusOutlined />} style={{ marginTop: 10, marginBottom: 10 }} onClick={() => add({
                        type: 'javascript'

                      })} block type='dashed'>添加后置操作</Button>
                    </div>
                  }}
                </Form.List>
                //                   <ProFormList
                //                     style={{ width: '100%' }}
                //                     copyIconProps={false}
                //                     itemContainerRender={doms=><Collapse>{doms}</Collapse>}
                //                     itemRender={({ listDom, action, },listMeta) => {
                //                       return <Collapse.Panel header={listMeta.field.name} key={listMeta.field.name}>
                //                         {listDom}
                //                       </Collapse.Panel>
                //                     }}
                //                     creatorButtonProps={{
                //                       creatorButtonText: '添加后置操作',
                //                     }}
                //                     name="postScript">
                //                       {(a,v)=>{
                // a.
                //                       }}
                //                     {/* <ProFormField style={{ width: '100%' }}>
                //                       <JsEditor />
                //                     </ProFormField> */}
                //                   </ProFormList>
              },
            ]}
          />
        </ProForm>
      </Spin>
    </Card>
  );
};
export default App;
